import React, { useState, useEffect } from 'react';
import { Table, Button, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import productService from '../../../../services/productService';
import type { Product } from '../../../../services/productService';
import type { WineItem } from '../types';

interface ProductSelectorProps {
  onImport: (products: WineItem[]) => void;
  selectedItems: WineItem[];
}

export const ProductSelector: React.FC<ProductSelectorProps> = ({
  onImport,
  selectedItems
}) => {
  const [loading, setLoading] = useState(false);
  const [products, setProducts] = useState<Product[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  useEffect(() => {
    loadProducts();
  }, []);

  useEffect(() => {
    // 设置已选商品
    setSelectedRowKeys(selectedItems.map(item => item.id));
  }, [selectedItems]);

  const loadProducts = async () => {
    setLoading(true);
    try {
      const response = await productService.getProductList({
        status: 1,
        canBuy: 1
      });
      if (response.code === 0 && response.data) {
        setProducts(response.data.list);
      } else {
        message.error('获取商品列表失败');
      }
    } catch (error) {
      message.error('获取商品列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleImport = () => {
    const selectedProducts = products.filter(product => 
      selectedRowKeys.includes(product.id)
    );

    const wineItems: WineItem[] = selectedProducts.map(product => ({
      id: String(product.id),
      name: product.title,
      brewery: '未知酒厂', // 这里需要根据实际数据结构调整
      price: product.price,
      category: product?.category?.name || '未分类',
      description: product.description,
      image: product.image,
      abv: '暂无数据' // 这里需要根据实际数据结构调整
    }));

    onImport(wineItems);
  };

  const columns: ColumnsType<Product> = [
    {
      title: '商品图片',
      dataIndex: 'image',
      key: 'image',
      width: 100,
      render: (image: string) => (
        <img src={image} alt="商品图片" style={{ width: 50, height: 50, objectFit: 'contain' }} />
      )
    },
    {
      title: '商品名称',
      dataIndex: 'title',
      key: 'title'
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (price: number) => `¥${price}`
    },
    {
      title: '分类',
      dataIndex: ['category', 'name'],
      key: 'category'
    }
  ];

  return (
    <div>
      <Table
        rowKey="id"
        loading={loading}
        columns={columns}
        dataSource={products}
        rowSelection={{
          selectedRowKeys,
          onChange: (newSelectedRowKeys) => {
            setSelectedRowKeys(newSelectedRowKeys);
          }
        }}
        pagination={{
          pageSize: 20,
          showTotal: (total) => `共 ${total} 条`
        }}
      />
      <div style={{ marginTop: 16, textAlign: 'right' }}>
        <Button
          type="primary"
          onClick={handleImport}
          disabled={selectedRowKeys.length === 0}
        >
          导入选中商品
        </Button>
      </div>
    </div>
  );
};

export default ProductSelector; 